// Package middleware
// @Author Spume
// @Date 2025-01-13 13:48

package middleware

import (
	"gitee.com/spume/common_service/app/billing/internal/model/do"
	"gitee.com/spume/common_service/app/billing/internal/service"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

type (
	sMiddleware struct{}
)

func init() {
	service.RegisterMiddleware(New())
}

func New() service.IMiddleware {
	return &sMiddleware{}
}

func (s *sMiddleware) CheckAuth(r *ghttp.Request) {
	ctx := r.GetCtx()
	tenantId := r.Get("tenantId").String()

	apiAuth, err := service.ApiAuth().Get(ctx, &do.ApiAuth{Key: tenantId})
	if err != nil {
		r.SetError(err)
		return
	}
	if g.IsEmpty(apiAuth) {
		err = gerror.New("key is error")
		r.SetError(err)
		return
	}

	r.Middleware.Next()
}
